package top.kikt.book.core.handlers.common

import okhttp3.HttpUrl.Companion.toHttpUrl
import org.jsoup.nodes.Document
import top.kikt.book.core.base.BookHandler
import top.kikt.book.core.entity.ChapterEntity
import top.kikt.book.core.entity.ChapterMetaEntity

interface ContentPagingHandler :BookHandler{


    fun parseContent(document: Document): String


    fun nextContentPageUrl(document: Document, url: String): String?


    fun handleChapter(chapterMetaEntity: ChapterMetaEntity): ChapterEntity? {
        val content = StringBuilder()

        var page = 1
        var currentPageUrl = chapterMetaEntity.url
        while (true) {
            val doc = currentPageUrl.toHttpUrl().toDocument() ?: throw Exception("Get next page failed")
            val bookText = parseContent(doc)
            content.append(bookText)
            val nextPageUrl = nextContentPageUrl(doc, currentPageUrl) ?: break
            currentPageUrl = nextPageUrl
            page++
        }

        println("${chapterMetaEntity.name} 共 ${content.count()} 字")

        return chapterMetaEntity.toChapterMetaEntity(content.toString())
    }


}